(function() {
  'use strict';

  const ApiServerUrls = {
    BASE_URL: 'http://81.27.85.129/api/f1/',
    getAllWorldChampionsUrl: () =>
      ApiServerUrls.BASE_URL + 'driverstandings/1.json?offset=55&limit=11',
    getAllRaceWinnersForYearUrl: (year) =>
      ApiServerUrls.BASE_URL + year + '/results/1.json?limit=999',
  };

  const Years = {
    START_YEAR: 2005,
    END_YEAR: 2015,
    getYears: function() {
      const years = [];
      for (let year = Years.START_YEAR; year <= Years.END_YEAR; year++) {
        years.push(year);
      }
      return years;
    },
    isYearInRange: function(year) {
      return Years.START_YEAR <= year && year <= Years.END_YEAR;
    },
  };

  const requestAllWorldChampions = ($scope, $http) => {
    const getAllWorldChampionNamesFromJson = json =>
      json.MRData.StandingsTable.StandingsLists
        .filter(({season}) => Years.isYearInRange(season))
        .map(({season, DriverStandings}) => {
          const driver = DriverStandings[0].Driver;
          return {
            year: season,
            displayName: driver.givenName + ' ' + driver.familyName
          };
        });

    $http.get(ApiServerUrls.getAllWorldChampionsUrl())
      .success(json =>
        $scope.championsData = getAllWorldChampionNamesFromJson(json)
      ).error(() => {
        // throw error here only to prevent excessive alerts
        alert('unable to connect to the ergast server');
      });
  };

  const requestAllRaceWinnersForYear= ($scope, $http, year) => {
    const getAllRaceWinnerNamesFromJson = json =>
      json.MRData.RaceTable.Races.map(
        ({round, Results}) => {
          const driver = Results[0].Driver;
          return {
            round: round * 1 < 10 ? '0' + round: round ,
            displayName: driver.givenName + ' ' + driver.familyName,
          };
        }
      );

    $http.get(ApiServerUrls.getAllRaceWinnersForYearUrl(year))
      .success(json =>
        $scope.winnersData[year] = getAllRaceWinnerNamesFromJson(json)
      );
  };

  angular.module('app', [])
    .controller('ListController', function ($scope, $http) {
      $scope.toggleItemExpansion = year => {
        if ($scope.highlightedYear === year) {
          $scope.highlightedYear = null;
        } else {
          $scope.highlightedYear = year;
        }
      };

      requestAllWorldChampions($scope, $http);

      $scope.winnersData = {};
      Years.getYears().forEach(
        year => requestAllRaceWinnersForYear($scope, $http, year)
      );
    });
})();
